<?php
/**
 * Created by PhpStorm.
 * User: wzy12
 * Date: 2018/9/25
 * Time: 13:20
 */

namespace app\common\model;


use think\Model;

class GoodsSpec extends Model
{
    public function operation($data){
        $query = $this -> where('spec_name', $data['spec_name']) -> where('model_id', $data['model_id']);
        $action = false;
        if(isset($data['id'])){
            $action = true;

            $query -> where('id', '<>', $data['id']);
        }
        // 判断是否已有该规格
        $res = $query -> value('id');
        if($res){
            return echoArr(0, '该模型下的这个规格已存在');
        }


        if($data['input_mode'] != 1){
            $data['spec_value'] = '';
        }else{
            if(!$data['spec_value']){
                return echoArr(0, '请填写可选值');
            }
            $data['spec_value'] = trim($data['spec_value']);
        }

        $result = $this -> validate(true) -> allowField(true) -> isUpdate($action) -> save($data);
        if(false === $result){
            return echoArr(0, $this -> getError());
        }else{
            return echoArr(1, '操作成功');
        }
    }

    public function resList($where){
        $query = $this -> where(1);

        // 筛选条件
        $is_where = $where;
        unset($is_where['page']);
        if($is_where) {
            if ($where) {
                // 查询模型
                if ($where['model_id']) {
                    $query->where('model_id', $where['model_id']);
                }
            }
        }

        // 规格
        $list = $query -> alias('s')
            -> join('goods_model m', 'm.id = s.model_id')
            -> field('s.*,m.model_name')
            -> order('id desc')
            -> paginate(10, false, ['query'=>request()->param()]);
        foreach($list as $k => $v){
            if($v['spec_value']){
                $list[$k]['spec_value'] = implode(', ', explode("\n", $v['spec_value']));
            }
        }

        // 模型
        $model = model('GoodsModel') -> select();

        $arr['list'] = $list;
        $arr['model'] = $model;
        return $arr;
    }

    public function del($data){
        $res = model('GoodsSpecValue') -> whereIn('spec_id', $data) -> select();

        $result = false;
        if(!$res){
            $result = $this -> destroy($data);
        }else{
            return echoArr(0, '请先去除拥有此规格的商品');
        }

        if(false === $result){
            return echoArr(0, '操作失败');
        }else{
            return echoArr(1, '操作成功');
        }
    }
}